package com.jiang.jixiang.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.NearbyNearbyMerchantBean;
import com.jiang.jixiang.bean.OrderInfoBean;
import com.jiang.jixiang.databinding.ActivityMyorderinfoBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.tools.PubDiaUtils;
import com.jiang.jixiang.ui.adapter.OrderInfoAdapter;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.countdown.CommitTimer;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.SpacesItemDecortion;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ToastUtils;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;

public class MyOrderInfoActivity extends BaseActivity implements NetWorkListener {
    private ActivityMyorderinfoBinding binding;
    private OrderInfoAdapter orderInfoAdapter;
    private List<String> data;
    private Bundle bundle;
    private int status;
    private String order_no;
    private OrderInfoBean orderInfoBean;
    private NearbyNearbyMerchantBean nearbyNearbyMerchantBean;
    private long seconds;
    private long minutes;
    private long hours;
    private String hoursStr;
    private String minutesStr;
    private String secondsStr;
    private String strCurrrentTime;
    private View viewStub;

    @Override
    protected void initCreate(Bundle savedInstanceState) {
        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        binding = ActivityMyorderinfoBinding.inflate(getLayoutInflater());
        // bindingFinsh = ActivityMyorderinfofinishBinding.inflate(getLayoutInflater());

        bundle = getIntent().getExtras();
        status = bundle.getInt("status");
        order_no = bundle.getString("order_no");
        LogcatUtils.e("status " + status);

        setContentView(binding.getRoot());
    }

    @Override
    protected void initView() {
        binding.titleTextTv.setText(R.string.order_details);
        binding.titleLeftBtn.setOnClickListener(view -> {
            finish();
        });


        binding.btnBuy.setChangeAlphaWhenPress(true);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3);
        binding.rcyData.addItemDecoration(new SpacesItemDecortion(10, 3));
        binding.rcyData.setLayoutManager(gridLayoutManager);
        orderInfoAdapter = new OrderInfoAdapter();

        binding.rcyData.setAdapter(orderInfoAdapter);

        orderInfoAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", orderInfoAdapter.getData().get(position).getId());
                pageJump(NearbySellerInfoActivity.class, bundle);
            }
        });


        binding.btnBuy.setOnClickListener(view -> {
            PubDiaUtils.getInstance().showTwoBtnDialog(getContext(), "", getString(R.string.payment_amount), getString(R.string.cancel), getString(R.string.sure), new PubDiaUtils.PublicDiaologCallback() {
                @Override
                public void onConfirm() {

                    buyPower();
                }

                @Override
                public void onCancel() {

                }
            });

        });

        showProgressDialog(false);
        polling();
        loadMerchant();
    }

    private void buyPower() {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        params.put("order_no", order_no);
        okHttpModel.post(ApiUrl.orderBuy_Api, params, ApiUrl.orderBuy_Api_ID, this);
    }

    private void loadMerchant() {

        Map<String, String> params = new HashMap<>();
        params.put("longitude", StringUtils.getString(getLocation().getLongitude()));
        params.put("latitude", StringUtils.getString(getLocation().getLatitude()));
        params.put("isList", "true");
        params.put("page_no", "1");
        params.put("page_size", "3");
        okHttpModel.post(ApiUrl.sellerList_Api, params, ApiUrl.sellerList_Api_ID, this);

    }

    /**
     * 查询订单状态
     */


    private void loadInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("order_no", order_no);
        okHttpModel.post(ApiUrl.orderInfo_Api, params, ApiUrl.orderInfo_Api_ID, this);

    }


    //轮询
    private Timer timer;

    private void polling() {
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new CommitTimer() {
            @Override
            public void run() {
                loadInfo();
            }
        }, 0, 3 * 1000);////Teask，延时时间，轮询间隔
    }


    @Override
    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {

            case ApiUrl.orderInfo_Api_ID://已完成
                orderInfoBean = GsonUtils.parseJObject(data.toString(), OrderInfoBean.class);
                if (orderInfoBean != null) {
                    if (orderInfoBean.getStatus() == 1) {
                        binding.tvItemNumberIng.setText(StringUtils.getString(getString(R.string.order_no), order_no));
                        binding.tvItemAmountIng.setText(orderInfoBean.getAmount());
                        binding.tvCurrrentTime.setText(orderInfoBean.getUse_time());
                        binding.llOrdering.setVisibility(View.VISIBLE);
                    } else {
                        if (timer != null) {
                            timer.purge();
                            timer.cancel();
                            timer = null;
                        }
                        BaseBusData busData = new BaseBusData(BusCode.finishOrder);
                        EventBusUtil.postEvent(busData);
                        binding.llOrdering.setVisibility(View.GONE);
                        if (orderInfoBean.getIs_buy() == 0) {
                            binding.llOrderFinish.setVisibility(View.VISIBLE);
                            binding.llOrderBuyFinish.setVisibility(View.GONE);
                            binding.tvRentalTime.setText(StringUtils.getString(orderInfoBean.getStart_time()));
                            binding.tvReturnTime.setText(StringUtils.getString(orderInfoBean.getEnd_time()));
                            binding.tvUsageTime.setText(StringUtils.getString(orderInfoBean.getUse_time()));
                            binding.tvRentalLocation.setText(StringUtils.getString(orderInfoBean.getStore_name()));
                            //binding.tvHomeLocation.setText(StringUtils.getString(orderInfoBean.getReturn_store()));
                            binding.tvBillingStandard.setText(StringUtils.getString(orderInfoBean.getBilling()));
                            binding.tvTatalRent.setText(orderInfoBean.getAmount());
                            binding.tvItemAmountFinish.setText(StringUtils.getString(order_no));
                        } else {
                            binding.llOrderFinish.setVisibility(View.GONE);
                            binding.llOrderBuyFinish.setVisibility(View.VISIBLE);
                            binding.tvBuyTime.setText(StringUtils.getString(orderInfoBean.getStart_time()));
                            binding.tvBuyAddress.setText(StringUtils.getString(orderInfoBean.getStore_name()));
                            //binding.tvBuyNum.setText(StringUtils.getString(orderInfoBean.getBuy_num()));
                            //binding.tvBuyMoney.setText(orderInfoBean.getAmount());
                            binding.tvItemAmountBuy.setText(StringUtils.getString(order_no));
                            //tvChargingBankNo.setText(StringUtils.getString(orderInfoBean.getBatterys().toString().replace("[", "").replace("]", "")));
                        }
                    }


                }


                break;


            case ApiUrl.sellerList_Api_ID:
                nearbyNearbyMerchantBean = GsonUtils.parseJObject(data.toString(), NearbyNearbyMerchantBean.class);
                if (nearbyNearbyMerchantBean != null) {
                    orderInfoAdapter.setList(nearbyNearbyMerchantBean.getList());
                }
                break;

            case ApiUrl.orderBuy_Api_ID:
                ToastUtils.showShort(commonality.getMessage());
                binding.llOrdering.setVisibility(View.GONE);
                binding.llOrderFinish.setVisibility(View.GONE);
                binding.llOrderBuyFinish.setVisibility(View.VISIBLE);
                if (timer != null) {
                    timer.purge();
                    timer.cancel();
                    timer = null;
                }
                showProgressDialog(false);
                loadInfo();
                break;
        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());

    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.toString());
    }


    @Override
    protected void FinishDesTroy() {
        ManageActivity.removeActivity(this.getClass().getSimpleName());
    }


    public String stringForTime(long timeMs) {
        //totalSeconds = timeMs / 1000;
        seconds = timeMs % 60;
        minutes = (timeMs / 60) % 60;
        hours = (timeMs / 3600) % 24;
        if (seconds < 10) {
            secondsStr = StringUtils.getString("0", seconds);
        } else {
            secondsStr = StringUtils.getString(seconds);
        }

        if (minutes < 10) {
            minutesStr = StringUtils.getString("0", minutes);
        } else {
            minutesStr = StringUtils.getString(minutes);
        }
        if (hours < 10) {
            hoursStr = StringUtils.getString("0", hours);
        } else {
            hoursStr = StringUtils.getString(hours);
        }

//        if (hours > 0) {
//            strCurrrentTime = StringUtils.getString(hoursStr, ":", minutesStr, ":", secondsStr);
//        } else {
//            strCurrrentTime = StringUtils.getString(minutesStr, ":", secondsStr);
//        }
        strCurrrentTime = StringUtils.getString(hoursStr, ":", minutesStr);
        LogcatUtils.e(" strCurrrentTime " + strCurrrentTime);
        return strCurrrentTime;
    }

}
